package com.edmendst.xmall.service.impl;

import com.edmendst.xmall.dto.ReviewInfo;
import com.edmendst.xmall.dto.ReviewReplyInfo;
import com.edmendst.xmall.mapper.*;
import com.edmendst.xmall.pojo.*;
import com.edmendst.xmall.service.ReviewService;
import com.edmendst.xmall.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
public class ReviewServiceImpl implements ReviewService {

    @Value("${review.image}")
    private String REVIEW_IMAGE_PATH;

    @Autowired
    private ReviewMapper reviewMapper;

    @Autowired
    private ReviewImageMapper reviewImageMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ReviewLikeMapper reviewLikeMapper;

    @Autowired
    private ReviewReplyMapper reviewReplyMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserService userService;


    @Override
    public String addReview(ReviewInfo reviewInfo, String userName, List<MultipartFile> reviewImages) {
        Integer productId = reviewInfo.getProductId();
        Integer userIdByUserName = userService.selectUserIdByUserName(userName);
        OrdersExample ordersExample = new OrdersExample();
        ordersExample.createCriteria().andUserIdEqualTo(userIdByUserName).andOrderIdEqualTo(reviewInfo.getOrderId());
        List<Orders> orders = ordersMapper.selectByExample(ordersExample);
        if (orders.isEmpty() || !orders.get(0).getOrderId().equals(reviewInfo.getOrderId())) {
            return "订单不存在";
        } else if (!orders.get(0).getOrderReceivedStatus()) {
            return "订单未收货";
        }
        if (userIdByUserName != null) {
            Review review = new Review();
            review.setUserId(userIdByUserName);
            review.setProductId(reviewInfo.getProductId());
            review.setReviewRating(reviewInfo.getReviewRating());
            review.setReviewContent(reviewInfo.getReviewContent());
            review.setOrderId(reviewInfo.getOrderId());
            int i = reviewMapper.insertSelective(review);

            Integer reviewId = review.getReviewId();
            int j = insertReviewImage(reviewId, reviewImages);
            if (i == 1 && j != -1) {
                return "success";
            } else if (i != 1) {
                return "评论失败";
            } else {
                return "图片上传失败";
            }
        }
        return "用户不存在";
    }

    @Override
    public List<ReviewInfo> getReviewList(Integer productId) {
        List<ReviewInfo> reviewInfos = new ArrayList<>();
        ReviewExample reviewExample = new ReviewExample();
        reviewExample.setOrderByClause("RAND()");
        reviewExample.createCriteria().andProductIdEqualTo(productId);
        List<Review> reviews = reviewMapper.selectByExampleWithBLOBs(reviewExample);
        for (Review review : reviews) {
            ReviewInfo reviewInfo = new ReviewInfo();
            reviewInfo.setReviewId(review.getReviewId());
            reviewInfo.setUserId(review.getUserId());
            reviewInfo.setUserName(userMapper.selectByPrimaryKey(review.getUserId()).getUserName());
            reviewInfo.setProductId(review.getProductId());
            reviewInfo.setReviewRating(review.getReviewRating());
            reviewInfo.setReviewContent(review.getReviewContent());
            reviewInfo.setReviewCreateTime(review.getReviewCreateTime());

            ReviewImageExample reviewImageExample = new ReviewImageExample();
            reviewImageExample.setOrderByClause("sort_order ASC");
            reviewImageExample.createCriteria().andReviewIdEqualTo(review.getReviewId());
            List<ReviewImage> reviewImages = reviewImageMapper.selectByExample(reviewImageExample);
            for (ReviewImage reviewImage : reviewImages) {
                reviewInfo.getReviewImageUrls().add(reviewImage.getImageUrl());
                reviewInfo.getReviewImageSortOrders().add(reviewImage.getSortOrder());
            }
            // 查询评论回复
            ReviewReplyExample replyExample = new ReviewReplyExample();
            replyExample.createCriteria().andReviewIdEqualTo(review.getReviewId());
            List<ReviewReply> replies = reviewReplyMapper.selectByExampleWithBLOBs(replyExample);

            for (ReviewReply reply : replies) {
                ReviewReplyInfo replyInfo = new ReviewReplyInfo();
                replyInfo.setReplyId(reply.getReplyId());
                replyInfo.setUserId(reply.getUserId());

                // 获取用户名
                User user = userMapper.selectByPrimaryKey(reply.getUserId());
                replyInfo.setUserName(user != null ? user.getUserName() : "已删除用户");

                replyInfo.setReplyContent(reply.getReplyContent());
                replyInfo.setReplyTime(reply.getReplyTime());
                replyInfo.setParentReplyId(reply.getParentReplyId());
                replyInfo.setIsSellerReply(reply.getIsSellerReply());
                reviewInfo.getReplies().add(replyInfo);
            }
            reviewInfos.add(reviewInfo);
        }
        return reviewInfos;
    }

    @Override
    public int reviewLike(Integer reviewId, String userName) {
        System.out.println("用户名：" + userName);
        Integer userIdByUserName = userService.selectUserIdByUserName(userName);

        if (userIdByUserName != null) {
            Review review = reviewMapper.selectByPrimaryKey(reviewId);
            if (review != null) {
                int i = reviewLikeMapper.selectReviewLike(reviewId, userIdByUserName);
                if (i == 0) {
                    reviewLikeMapper.insertReviewLike(reviewId, userIdByUserName);
                    return 1;
                }else
                {
                    reviewLikeMapper.deleteReviewLike(reviewId, userIdByUserName);
                    return -1;
                }
            }
        }
        return 0;
    }

    @Override
    public String reviewReply(ReviewReplyInfo reviewReplyInfo, String userName) {
        Integer userIdByUserName = userService.selectUserIdByUserName(userName);
        ReviewReply reviewReply = new ReviewReply();
        reviewReply.setUserId(userIdByUserName);
        reviewReply.setReviewId(reviewReplyInfo.getReviewId());
        reviewReply.setReplyContent(reviewReplyInfo.getReplyContent());
        if (reviewReplyInfo.getParentReplyId() == null || reviewReplyInfo.getParentReplyId() == 0) {
            reviewReply.setParentReplyId(null);
        } else {
            reviewReply.setParentReplyId(reviewReplyInfo.getParentReplyId());
        }
        String userType = userMapper.selectByPrimaryKey(userIdByUserName).getUserType();
        if ("seller".equals(userType) || "both".equals(userType)) {
            reviewReply.setIsSellerReply(true);
        } else {
            reviewReply.setIsSellerReply(false);
        }
        reviewReplyMapper.insertSelective(reviewReply);
        return "评论添加成功";
    }

    public int insertReviewImage(Integer reviewId, List<MultipartFile> reviewImages) {
        int i = 0;
        final String[] ALLOWED_EXT = {".png", ".jpg", ".jpeg", ".gif"};
        for (MultipartFile multipartFile : reviewImages) {
            if (multipartFile.isEmpty() || multipartFile.getSize() == 0) {
                continue;
            }
            try {
                String filename = multipartFile.getOriginalFilename();
                String fileExt = filename.substring(filename.lastIndexOf(".")).toLowerCase();
                if (!Arrays.asList(ALLOWED_EXT).contains(fileExt)) {
                    throw new IllegalArgumentException("不支持的文件类型");
                }

                Path path = Paths.get(REVIEW_IMAGE_PATH, reviewId.toString());
                Files.createDirectories(path);

                String newFileName = UUID.randomUUID() + fileExt;
                Path targetPath = path.resolve(newFileName);

                try (InputStream is = multipartFile.getInputStream()) {
                    Files.copy(is, targetPath, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
                }

                String relativePath = reviewId + "/" + newFileName;
                ReviewImage reviewImage = new ReviewImage();
                reviewImage.setReviewId(reviewId);
                reviewImage.setImageUrl(relativePath);
                reviewImage.setSortOrder(i);
                reviewImageMapper.insertSelective(reviewImage);
                i++;
            } catch (IOException e) {
                throw new RuntimeException("文件上传失败: " + e.getMessage());
            }
            return i;
        }
        return -1;
    }
}
